<template>
  <div class="menu-manage">
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd">新增菜单</el-button>
    </div>

    <el-table
      :data="menuList"
      row-key="id"
      border
      default-expand-all
      :tree-props="{
        children: 'children',
        hasChildren: 'hasChildren'
      }"
    >
      <el-table-column prop="title" label="菜单名称" min-width="180">
        <template #default="{ row }">
          <span>
            <el-icon v-if="row.icon" class="menu-icon">
              <component :is="row.icon" />
            </el-icon>
            {{ row.title }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="菜单标识" min-width="180" />
      <el-table-column prop="path" label="路由路径" min-width="180" />
      <el-table-column prop="component" label="组件路径" min-width="180" />
      <el-table-column prop="order" label="排序" width="80" align="center" />
      <el-table-column label="显示" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.is_show ? 'success' : 'info'">
            {{ row.is_show ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑菜单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑菜单' : '新增菜单'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="menuForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="menuForm.title" />
        </el-form-item>
        <el-form-item label="菜单标识" prop="name">
          <el-input v-model="menuForm.name" />
        </el-form-item>
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="menuForm.path" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <icon-select v-model="menuForm.icon" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="menuForm.component" />
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input-number v-model="menuForm.order" :min="0" />
        </el-form-item>
        <el-form-item label="上级菜单" prop="parent_id">
          <el-tree-select
            v-model="menuForm.parent_id"
            :data="menuOptions"
            clearable
            check-strictly
            :render-after-expand="false"
            placeholder="请选择上级菜单"
          />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch v-model="menuForm.is_show" />
        </el-form-item>
        <el-form-item label="是否缓存">
          <el-switch v-model="menuForm.is_cache" />
        </el-form-item>
        <el-form-item label="是否日志">
          <el-switch v-model="menuForm.is_log" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import IconSelect from '@/components/IconSelect.vue'
import http from '@/utils/http'

const menuList = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const menuForm = reactive({
  id: null,
  name: '',
  title: '',
  icon: '',
  path: '',
  component: '',
  redirect: '',
  order: 0,
  is_show: true,
  is_cache: true,
  is_log: true,
  parent_id: null
})

const rules = {
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }]
}

// 获取菜单列表
const fetchMenuList = async () => {
    const menu_tree = await http.get('/menus/tree')
    menuList.value = menu_tree
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(menuForm, {
    id: null,
    name: '',
    title: '',
    icon: '',
    path: '',
    component: '',
    redirect: '',
    order: 0,
    is_show: true,
    is_cache: true,
    is_log: true,
    parent_id: null
  })
}

// 新增菜单
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
  
}

// 编辑菜单
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(menuForm, row)
  dialogVisible.value = true
}

// 删除菜单
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该菜单吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await http.delete(`/menus/${row.id}`)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        await fetchMenuList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate()
    const method = isEdit.value ? 'put' : 'post'
    const url = isEdit.value ? `/menus/${menuForm.id}` : '/menus'
    await http[method](url, menuForm)
    dialogVisible.value = false
    await fetchMenuList()
}

// 计算菜单选项
const menuOptions = computed(() => {
  const transformData = (data) => {
    return data.map(item => ({
      value: item.id,
      label: item.title,
      children: item.children ? transformData(item.children) : []
    }))
  }
  return transformData(menuList.value)
})

onMounted(() => {
  fetchMenuList()
})
</script>

<style scoped>
.menu-manage {
  padding: 20px;
}
.header-actions {
  margin-bottom: 20px;
}
.menu-icon {
  margin-right: 8px;
  vertical-align: middle;
}
</style>